#!/bin/bash

# 创建Dockerfile
function createDockerfile() {
    war_dir=(`find . -name "*.war"`) #查找到相应的war包
    for i in ${war_dir[*]}
    do
        # 获取war所在的相对文件夹
        app_dir=`echo "$i" | awk -F [.] '{print $2}' | sed -n 's/^\///p'` 
        app=`echo "$app_dir" | awk -F [/] '{print $NF}'`
        if [ "$1" == "$app" ];then
            if [ -f "Dockerfile.$app" ];then
                echo "Dockerfile.$app"
                break
            else
                cat >> Dockerfile.$app << EOF
FROM hymax_tomcat
COPY $app_dir /opt/tomcat/webapps/$app
RUN mkdir /data
COPY run.sh /data/
RUN chmod +x /data/run.sh
ENTRYPOINT ["/bin/sh","-c","/data/run.sh $app"]

EOF
            echo "Dockerfile.$app"                
            fi
        else
            continue
        fi
    done
}

# 生成image和启动container
function buildApp() {
    APP=$1
    echo "@hello hymax etc. "
    
    if [ -e "Dockerfile.${APP}" ];then
		rm -rf "Dockerfile.${APP}"
		echo "Dockerfile.${APP}"
	fi
    
    DOCKERFILE=`createDockerfile ${APP}`
    IMAGE_NAME=`echo ${APP} | tr [A-Z] [a-z]`
    echo ${IMAGE_NAME}
    echo ${DOCKERFILE}
    docker build -t ${IMAGE_NAME} -f ${DOCKERFILE} .
    if [ `docker ps -a | grep -v "NAME" | awk '{print $NF}' | grep -w ${IMAGE_NAME} | wc -l` -ne 0 ];then
        docker rm -f ${IMAGE_NAME}
    fi
    docker run -d -p 57006:8080 -it --name=${IMAGE_NAME} --link hymax_solr:solr_db --link hymax_mongo:mongo_db --link hymax_redis:redis_db --link hymax_mysql:mysql_db --link hymax_zookeeper:zookeeper_db -v /home/volumes/tomcat/server.xml:/opt/tomcat/conf/server.xml ${IMAGE_NAME}
    
}

#删除none容器
docker rmi $(docker images | grep "^<none>" | awk "{print $3}")

#执行主方法
buildApp $1